﻿using LJX.SmartPark.Common.Extensions;
using LJX.SmartPark.Common.ResponseOutput;
using LJX.SmartPark.Domain.IotInfo;
using LJX.SmartPark.Domain.SysManage;
using LJX.SmartPark.EntityFramework;
using LJX.SmartPark.Service.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJX.SmartPark.Service.SysManage
{
    public class RoleManageService : IRoleManageService
    {
        private readonly IRepository<RoleManage> _studentService;

        private readonly StudentServerContext _context;

        public RoleManageService(IRepository<RoleManage> studentService, StudentServerContext context)
        {
            _studentService = studentService;
            _context = context;
        }

        public async Task<Response<bool>> DeleteByIdAsync(RoleManage input)
        {
            var result = await _studentService.DeleteByIdAsync(input.MapTo<RoleManage>());
            List<RoleMenu> list = _context.RoleMenu.Where(x => x.RoleId == input.Id).ToList();
            _context.RemoveRange(list);
            _context.SaveChanges(); 
            return Response<bool>.Ok(result > 0);
        }

        public async Task<Response<List<RoleManage>>> GetRoleManageAsync(RoleForm form)
        {
            var students = await _studentService.GetAllListAsync();
            if (!string.IsNullOrEmpty(form.roleName))
            {
                students = students.Where(x => x.RoleName.Contains(form.roleName)).ToList();
            }
            var count = students.Count();
            students = students.Skip((form.pageIndex - 1) * form.pageSize).Take(form.pageSize).ToList();
            var result = students.MapToList<RoleManage>();
            return Response<List<RoleManage>>.Ok(result, count);
        }

        public async Task<Response<bool>> PostAddRoleManage(RoleManage input)
        {
            var result = _studentService.InsertAsyncById(input.MapTo<RoleManage>());

            return Response<bool>.Ok(result.Result > 0);
        }

        public async Task<Response<bool>> PutUpdateRoleManage(RoleManage input)
        {
            var result = _studentService.UpdateAsync(input.MapTo<RoleManage>());

            return Response<bool>.Ok(result.Result > 0);
        }
    }
}
